package com.beiben.statistics.service.impl;

import com.beiben.statistics.ServiceUtils;
import com.beiben.statistics.mapper.WorkMapper;
import com.beiben.statistics.service.IWorkService;
import com.beiben.statistics.vo.LineDataVo;
import com.beiben.statistics.vo.NameValueVo;
import com.beiben.statistics.vo.RecordSearchParamVo;
import com.beiben.statistics.vo.WorkItemVo;
import com.beiben.utils.DateUtil;
import com.beiben.work.process.domain.FileProcessUser;
import com.ruoyi.common.utils.Arith;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by admin on 2020/10/9.
 */
@Service
public class WorkServiceImpl implements IWorkService {

    @Autowired
    private WorkMapper workMapper;


    //查询统计所的总工作工时
    @Override
    public List<NameValueVo> selectWorkDeptSuo(RecordSearchParamVo recordSearchParamVo) throws ParseException {
        List<NameValueVo> resultList = null;
        ServiceUtils.setSearchTime(recordSearchParamVo);
        List<WorkItemVo> list = workMapper.selectWorkDeptSuo(recordSearchParamVo);
        resultList = ServiceUtils.resultList(recordSearchParamVo, list);
        return resultList;
    }

    //查询统计科室的总工作工时
    @Override
    public List<NameValueVo> selectWorkDeptShi(RecordSearchParamVo recordSearchParamVo) throws ParseException {
        List<NameValueVo> resultList = null;
        ServiceUtils.setSearchTime(recordSearchParamVo);
        List<WorkItemVo> list = workMapper.selectWorkDeptShi(recordSearchParamVo);
        resultList = ServiceUtils.resultList(recordSearchParamVo, list);
        return resultList;
    }

    /*
     * 查询所的平均工作工时
     *  */
    @Override
    public List<NameValueVo> selectAbilityDeptAverageSuo(RecordSearchParamVo recordSearchParamVo) throws ParseException {
        List<NameValueVo> list = selectWorkDeptSuo(recordSearchParamVo);
        List<NameValueVo> plist = workMapper.selectWorkHoursPeopleSuo(recordSearchParamVo);
        list = setValue(list, plist, recordSearchParamVo);
        list.sort(Comparator.comparing(NameValueVo::getValue).reversed());
        return list;
    }

    /*
     * 查询统计科室的平均工作工时
     * */
    @Override
    public List<NameValueVo> selectAbilityDeptAverageShi(RecordSearchParamVo recordSearchParamVo) throws ParseException {
        List<NameValueVo> list = selectWorkDeptShi(recordSearchParamVo);
        List<NameValueVo> plist = workMapper.selectWorkHoursPeopleShi(recordSearchParamVo);
        list = setValue(list, plist, recordSearchParamVo);
        list.sort(Comparator.comparing(NameValueVo::getValue).reversed());
        return list;
    }

    /*
     * 计算所和科室工作饱和度
     * */
    public List<NameValueVo> setValue(List<NameValueVo> list, List<NameValueVo> plist, RecordSearchParamVo recordSearchParamVo) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        long day = DateUtil.getDatePoorDay(sdf.parse(recordSearchParamVo.getEndTime()), sdf.parse(recordSearchParamVo.getBeginTime())) + 1;
        for (NameValueVo nv : list) {
            for (NameValueVo n : plist) {
                if (n.getId().equals(nv.getId())) {
                    nv.setHours(n.getHours());
                }
            }
            Double value = Arith.mul(Arith.div(Arith.div(nv.getValue(), day, 4), nv.getHours(), 4), 100);
            nv.setValue(value);
        }
        return list;
    }

    /*
     * 查询人员总工作工时
     * */
    @Override
    public List<NameValueVo> selectWorkTotalPeople(RecordSearchParamVo recordSearchParamVo) throws ParseException {
        List<NameValueVo> resultList = null;
        ServiceUtils.setSearchTime(recordSearchParamVo);
        List<WorkItemVo> list = workMapper.selectWorkTotalPeople(recordSearchParamVo);
        resultList = ServiceUtils.resultList(recordSearchParamVo, list);
        return resultList;
    }

    /*
     * 查询人员总工作饱和度
     * */
    @Override
    public List<NameValueVo> selectWorkAvgPeople(RecordSearchParamVo recordSearchParamVo) throws ParseException {
        List<NameValueVo> list = selectWorkTotalPeople(recordSearchParamVo);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        long day = DateUtil.getDatePoorDay(sdf.parse(recordSearchParamVo.getEndTime()), sdf.parse(recordSearchParamVo.getBeginTime())) + 1;
        for (NameValueVo nv : list) {
            Double value = Arith.mul(Arith.div(Arith.div(nv.getValue(), day, 4), nv.getHours(), 4), 100);
            nv.setValue(value);
        }
        list.sort(Comparator.comparing(NameValueVo::getValue).reversed());
        return list;
    }

    /*
     * 查询人员工作总量曲线图
     * */
    @Override
    public List<LineDataVo> selectWorkLinePeople(RecordSearchParamVo recordSearchParamVo) throws ParseException {
        //当前用户名、用户Id
        if(null==recordSearchParamVo.getUserId()){
            recordSearchParamVo.setUserId(recordSearchParamVo.getDeptId());
        }
        ServiceUtils.setLineSearchTime(recordSearchParamVo);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<FileProcessUser> listProcessUser = workMapper.selectFileProcessUserList(recordSearchParamVo);
        List<LineDataVo> lineDataList = new ArrayList<LineDataVo>();
        Date searchBeginTime = sdf.parse(recordSearchParamVo.getBeginTime());
        Date searchEndTime = sdf.parse(recordSearchParamVo.getEndTime());
        String name = "";
        Long userId = null;
        if(listProcessUser.size()>0){
             name = listProcessUser.get(0).getUser().getNickName();
             userId = listProcessUser.get(0).getUserId();
        }
        // TODO: 2020/10/27 遍历数组拆分工时，将工时拆分到每一天上，并删除查询时间外的数据
        for (FileProcessUser lp : listProcessUser) {
            Date startTime = lp.getStartTime();
            Date finishTime = lp.getFinishTime();
            // 计算天数时间差
            long day = DateUtil.getDatePoorDay(finishTime, startTime) + 1;
            // 每日文件时长
            double reCount = Arith.div(Double.valueOf(String.valueOf(lp.getFileHours())), day, 2);
            for (int i = 0; i < day; i++) {
                //获取指定日期前的日期
                Date relTime = DateUtil.getDatePoorDayReDate(startTime, -i, "yyyy-MM-dd");
                //实际时间- 查询开始时间
                Long poorStart = DateUtil.getDateMinus(relTime, searchBeginTime);
                //实际时间 - 查询结束时间
                Long poorEnd = DateUtil.getDateMinus(relTime, searchEndTime);
                //在查询时间端内的数据
                if (poorStart >= 0 && poorEnd <= 0) {
                    LineDataVo lineData = new LineDataVo();
                    lineData.setTime(sdf.format(relTime));
                    lineData.setValue(reCount);
                    lineDataList.add(lineData);
                }
            }
        }
        // TODO: 2020/10/27 根据时间进行聚合数组
        Map<String, List<LineDataVo>> groupByTimeMap = lineDataList.stream().collect(Collectors.groupingBy(LineDataVo::getTime));

        long day = DateUtil.getDatePoorDay(searchEndTime, searchBeginTime);
        List<LineDataVo> ldlist = new ArrayList<>();
        // TODO: 2020/10/27 补充没有工作量的日期，并对存在的工作量加和
        Double value;

        for (int i = 0; i < day; i++) {
            String relTime = DateUtil.getDatePoorDay(searchBeginTime, -i, "yyyy-MM-dd");
            LineDataVo ldv = new LineDataVo();
            List<LineDataVo> list = groupByTimeMap.get(relTime);
            value = 0.0;
            if (list != null && list.size() != 0) {
                for (LineDataVo lv : list) {
                    value += lv.getValue();
                }
            }
            ldv.setName(name);
            ldv.setUserId(userId);
            ldv.setTime(relTime);
            ldv.setValue(Arith.div(value, 1, 2));
            ldlist.add(ldv);
        }

        // TODO: 2020/10/27 根据日期排序
        if (ldlist.size() > 0) {
            ldlist.sort(Comparator.comparing(LineDataVo::getTime));
        } else {
            ldlist = null;
        }
        return ldlist;
    }

    /**
     * 查询人员工作饱和度曲线（近30天）
     */
    @Override
    public List<LineDataVo> selectWorkAvgLinePeople(RecordSearchParamVo recordSearchParamVo) throws ParseException {
        recordSearchParamVo.setUserId(recordSearchParamVo.getDeptId());
        List<LineDataVo> list = selectWorkLinePeople(recordSearchParamVo);
        Integer hours = workMapper.selectUserWorkHours(recordSearchParamVo);
        if (null != list) {
            for (LineDataVo l : list) {
                l.setValue(Arith.mul(Arith.div(l.getValue(), hours, 4), 100));
            }
        }
        return list;
    }

    /**
     * 查询统计所的质量问题统计（近30天）
     */
    @Override
    public List<NameValueVo> selectWorkQualityCount(RecordSearchParamVo recordSearchParamVo) throws ParseException {
        ServiceUtils.setSearchTime(recordSearchParamVo);
        return workMapper.selectWorkQualityCount(recordSearchParamVo);
    }

    /**
     * 查询统计科室的质量问题统计（近30天）
     */
    @Override
    public List<NameValueVo> selectWorkQualityCountShi(RecordSearchParamVo recordSearchParamVo) throws ParseException {
        ServiceUtils.setSearchTime(recordSearchParamVo);
        return workMapper.selectWorkQualityCountShi(recordSearchParamVo);
    }

    /**
     * 查询统计组的质量问题统计（近30天）
     */
    @Override
    public List<NameValueVo> selectWorkQualityCountZu(RecordSearchParamVo recordSearchParamVo) throws ParseException {
        ServiceUtils.setSearchTime(recordSearchParamVo);
        return workMapper.selectWorkQualityCountZu(recordSearchParamVo);
    }

    /**
     * 查询统计组的质量问题统计（近30天） 排名前十
     */
    @Override
    public List<NameValueVo> selectWorkQualityCountZuRank(RecordSearchParamVo recordSearchParamVo) throws ParseException {
        ServiceUtils.setSearchTime(recordSearchParamVo);
        return workMapper.selectWorkQualityCountZuRank(recordSearchParamVo);
    }

    /**
     * 按所统计总工作量（个数）
     */
    @Override
    public List<NameValueVo> selectWorkCountSuo(RecordSearchParamVo recordSearchParamVo) throws ParseException {
        ServiceUtils.setSearchTime(recordSearchParamVo);
        return workMapper.selectWorkCountSuo(recordSearchParamVo);
    }

    /**
     * 按科室统计总工作量（个数）
     */
    @Override
    public List<NameValueVo> selectWorkCountShi(RecordSearchParamVo recordSearchParamVo) throws ParseException {
        ServiceUtils.setSearchTime(recordSearchParamVo);
        return workMapper.selectWorkCountShi(recordSearchParamVo);
    }

    /**
     * 按人员统计总工作量（个数）
     */
    @Override
    public List<NameValueVo> selectWorkCountPeople(RecordSearchParamVo recordSearchParamVo) throws ParseException {
        ServiceUtils.setSearchTime(recordSearchParamVo);
        return workMapper.selectWorkCountPeople(recordSearchParamVo);
    }

    /**
     * 查询质量问题曲线（近30天）
     */
    @Override
    public List<NameValueVo> selectTotalLineQuality(RecordSearchParamVo recordSearchParamVo) throws ParseException {
        ServiceUtils.setLineSearchTime(recordSearchParamVo);
        List<NameValueVo> list = workMapper.selectFileProcessQualityList(recordSearchParamVo);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date searchBeginTime = sdf.parse(recordSearchParamVo.getBeginTime());
        Date searchEndTime = sdf.parse(recordSearchParamVo.getEndTime());
        // TODO: 2020/10/27 补充没有质量问题的日期
        List<NameValueVo> resultList = new ArrayList<NameValueVo>();
        long day = DateUtil.getDatePoorDay(searchEndTime,searchBeginTime);
        for(int i=0;i<day;i++) {
            NameValueVo ldv = new NameValueVo();
            String relTime = DateUtil.getDatePoorDay(searchBeginTime, -i, "yyyy-MM-dd");
            ldv.setName(relTime);
            for (NameValueVo l : list) {
                long poor = DateUtil.getDatePoorDay(sdf.parse(l.getName()),sdf.parse(relTime));
                if (poor==0) {
                    ldv.setValue(l.getValue());
                    break;
                }else{
                    ldv.setValue(0.0);
                }
            }
            if(null == ldv.getValue()){
                ldv.setValue(0.0);
            }
            resultList.add(ldv);
        }
        // TODO: 2020/10/27 根据日期排序
        if(resultList.size()>0&&resultList.size()>0){
            resultList.sort(Comparator.comparing(NameValueVo::getName));
        }else{
            resultList= null;
        }
        return resultList;
    }

    /**
     * 查询我的待办工作-日常工作
     */
    @Override
    public List<FileProcessUser> selectMyWaitWorkList(RecordSearchParamVo recordSearchParamVo) {
        ServiceUtils.setSearchTime(recordSearchParamVo);
        return workMapper.selectMyWaitWorkList(recordSearchParamVo);
    }

    /**
     * 我的待办工作-项目工作
     *
     * @param recordSearchParamVo
     * @return
     */
    @Override
    public List<FileProcessUser> selectMyWaitWorkProjectList(RecordSearchParamVo recordSearchParamVo) {
        ServiceUtils.setSearchTime(recordSearchParamVo);
        return workMapper.selectMyWaitWorkProjectList(recordSearchParamVo);
    }

    /**
     * 我的代办工作统计
     *
     * @return
     */
    @Override
    public Map<String, Object> selectCountWork(RecordSearchParamVo recordSearchParamVo) {
        ServiceUtils.setSearchTime(recordSearchParamVo);
        return workMapper.selectCountWork(recordSearchParamVo);
    }
    /**
     * 查询工作-日常工作-质量问题工作
     */
    @Override
    public List<FileProcessUser> selectQualityWorkList(RecordSearchParamVo recordSearchParamVo) {
        ServiceUtils.setSearchTime(recordSearchParamVo);
        recordSearchParamVo.setIsDesignProblem("Y");
        return workMapper.selectMyWaitWorkList(recordSearchParamVo);
    }
    /**
     * 工作统计 - 质量问题
     *
     * @return
     */
    @Override
    public Map<String, Object> selectQualityCountWork(RecordSearchParamVo recordSearchParamVo) {
        ServiceUtils.setSearchTime(recordSearchParamVo);
        recordSearchParamVo.setIsDesignProblem("Y");
        return workMapper.selectCountWork(recordSearchParamVo);
    }


}


